package edu.whut.mall.common.util;

import edu.whut.mall.common.constant.WxPayConstant;
import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;


public class WeixinPayUtils {

    private static Logger logger = Logger.getLogger(WeixinPayUtils.class);


    /**
     * 判断签名是否正确
     * @param xmlStr
     * @param key
     * @return
     * @throws Exception
     */
    public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
        Map<String, String> data =WxPayKit.toMap(xmlStr);
        if (!data.containsKey(WxPayConstant.FIELD_SIGN) ) {
            return false;
        }
        String sign = data.get(WxPayConstant.FIELD_SIGN);
        return generateSignature(data, key).equals(sign);
    }


    /**
     * 生成签名.
     *
     * @param data 待签名数据
     * @param key API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WxPayConstant.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);

        logger.info("__________generate sign__________");
        return EncryptUtil.md5(sb.toString()).toUpperCase();
    }

    /**
     * 从请求中读取出字符串
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static String readFromInputStream(InputStream inputStream) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        String result =  new String(byteArrayOutputStream.toByteArray(), "utf-8");
        byteArrayOutputStream.close();
        inputStream.close();
        return result;
    }



}
